import datetime
import os

from flask import Flask, make_response, request, session

app = Flask(__name__)
# 启用session
app.config['SECRET_KEY'] = os.urandom(24)


@app.route('/')
def hello_word():
    return 'flask我又来了'


@app.route('/cookie')
def cookie():
    response = make_response('设置成功')
    expire_time = datetime.datetime.now() + datetime.timedelta(days=1)
    response.set_cookie('name', 'dazhou', expires=expire_time)
    response.set_cookie('sex', 'male', expires=expire_time)
    response.set_cookie('city', 'beijing', expires=expire_time)

    return response


@app.route('/get_cookie')
def get_cookie():
    name = request.cookies.get('name')
    print(name)
    cookies = request.cookies
    print(cookies)
    cookies_dict = request.cookies.to_dict()
    for k, v in cookies_dict.items():
        print(k, v)
    return '获取cookie成功'


@app.route('/del_cookie')
def delete_cookie():
    response = make_response('删除cookie成功')
    # response.delete_cookie('name')

    cookies_dict = request.cookies.to_dict()
    for k, v in cookies_dict.items():
        response.delete_cookie(k)

    return response


@app.route('/add_session')
def add_session():
    session['username'] = 'xiaohao'
    session['nickname'] = 'haosir'
    session['role'] = 'admin'
    return 'session设置成功'


@app.route('/get_session')
def get_session():
    username = session.get('username')
    return 'session获取成功' + username


@app.route('/del_session')
def delete_session():
    session.clear()
    return 'session清除成功'


if __name__ == '__main__':
    app.run(debug=True)
